package com.Nahida.NaHome.util;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.Nahida.NaHome.activity.ShowTextActivity;

import org.json.JSONException;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class MsgUtil {
    private static Toast toast;

    public static void showMsg(String str, Context context) {
        toast(str, context);
    }

    public static void showMsgLong(String str, Context context) {
        toastLong(str, context);
    }

    public static void toast(String str, Context context) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            CenterThreadPool.runOnUiThread(() -> {
                toastInternal(str, context);
            });
        } else {
            toastInternal(str, context);
        }
    }

    public static void toastLong(String str, Context context) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            CenterThreadPool.runOnUiThread(() -> {
                toastLongInternal(str, context);
            });
        } else {
            toastLongInternal(str, context);
        }
    }

    private static void toastInternal(String str, Context context) {
        if (toast != null) toast.cancel();
        toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
        toast.show();
    }

    private static void toastLongInternal(String str, Context context) {
        if (toast != null) toast.cancel();
        toast = Toast.makeText(context, str, Toast.LENGTH_LONG);
        toast.show();
    }


    public static void err(Throwable e, Context context) {
        Log.e("ERROR", e.getMessage(), e);
        if (e instanceof IOException) showMsg("网络错误(＃°Д°)", context);
        else if (e instanceof JSONException) {
            if (SharedPreferencesUtil.getBoolean("develop_error_detailed", false)) {
                Writer writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                e.printStackTrace(printWriter);
                showText(context, "数据解析错误", writer.toString());
            }
            else
                showMsgLong("数据解析错误：\n" + e.toString().replace("org.json.JSONException:", ""), context);
        } else showMsgLong("错误：" + e, context);
    }

    public static void showText(Context context, String title, String text) {
        Intent testIntent = new Intent()
                .setClass(context, ShowTextActivity.class)
                .putExtra("title", title)
                .putExtra("content", text);
        context.startActivity(testIntent);
    }

}
